package com.huangd.platform.common.utils;

import com.huangd.platform.common.exception.RRException;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.JavaType;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class JsonUtils {

	public static final ObjectMapper DEFAULT = new ObjectMapper();

	public static String toJson(ObjectMapper mapper, Object obj) throws Exception {
		return mapper.writeValueAsString(obj);
	}

	public static <T> T fromJson(ObjectMapper mapper, String json, Class<T> cls) throws Exception {
		return mapper.readValue(json, cls);
	}

	public static <K, V> Map<K, V> fromJsonMap(ObjectMapper mapper, String json, Class<K> clsk, Class<V> clsv) throws Exception {
		JavaType type = JsonUtils.DEFAULT.getTypeFactory().constructParametricType(HashMap.class, clsk, clsv);
		return mapper.readValue(json, type);
	}

	@SuppressWarnings("rawtypes")
	public static <T, K, V> T fromJsonMap(ObjectMapper mapper, String json, Class<? extends Map> cls, Class<K> clsk, Class<V> clsv) throws Exception {
		JavaType type = JsonUtils.DEFAULT.getTypeFactory().constructParametricType(cls, clsk, clsv);
		return mapper.readValue(json, type);
	}

	public static <E> List<E> fromJsonList(ObjectMapper mapper, String json, Class<E> cls) {
		JavaType type = JsonUtils.DEFAULT.getTypeFactory().constructParametricType(ArrayList.class, cls);
		try {
			return mapper.readValue(json, type);
		} catch (IOException e) {
			e.printStackTrace();
			throw new RRException("json转换出错");
		}
	}

	@SuppressWarnings("rawtypes")
	public static <E> List<E> fromJsonList(ObjectMapper mapper, String json, Class<? extends List> cls, Class<E> clso) throws Exception {
		JavaType type = JsonUtils.DEFAULT.getTypeFactory().constructParametricType(cls, clso);
		return mapper.readValue(json, type);
	}

	public static String toJson(Object obj) {
		try {
			return toJson(DEFAULT, obj);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RRException("解析出错");

		}
	}

	public static <T> T fromJson(String json, Class<T> cls) {
		try {
			return fromJson(DEFAULT, json, cls);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RRException("解析出错");

		}

	}

	public static <K, V> Map<K, V> fromJsonMap(String json, Class<K> clsk, Class<V> clsv) throws Exception {
		return fromJsonMap(DEFAULT, json, clsk, clsv);
	}

	@SuppressWarnings("rawtypes")
	public static <T, K, V> T fromJsonMap(String json, Class<? extends Map> cls, Class<K> clsk, Class<V> clsv) throws Exception {
		return fromJsonMap(DEFAULT, json, cls, clsk, clsv);
	}

	public static <E> List<E> fromJsonList(String json, Class<E> cls){
		return fromJsonList(DEFAULT, json, cls);
	}

	@SuppressWarnings("rawtypes")
	public static <E> List<E> fromJsonList(String json, Class<? extends List> cls, Class<E> clso) throws Exception {
		return fromJsonList(DEFAULT, json, cls, clso);
	}
}
